package com.lzq.treefold.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.lzq.treefold.entity.File;
import com.lzq.treefold.mapper.FileMapper;
import com.lzq.treefold.service.IFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lzq
 * @since 2025-06-06
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService {

    @Override
    public List<File> listSonFiles(Long foldId) {
        List<File> list = lambdaQuery().eq(File::getFatherId, foldId).list();
        return list;
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        // 判斷是否存在
        File file = getById(id);
        if (file == null) {
            return false;
        }
        // 判断是文件
        removeById(id);
        if (file.getType() == 2) {
            return true;
        }
        // 文件夹还需要删除子文件

        deleteFold(file.getId());

        lambdaUpdate().eq(File::getId, file.getFatherId()).setSql("file_num = file_num + 1").update();

        return true;
    }

    @Override
    @Transactional
    public boolean add(File file) {
        // 判断该目录下面是否存在相同名称相同类型文件
        List<File> list = lambdaQuery().eq(File::getFatherId, file.getFatherId()).eq(File::getType, file.getType()).eq(File::getName, file.getName()).list();
        if (list.size() > 0) {
            return false;
        }
        // 添加
        file.setFileNum(0);
        save(file);
        // 更新父节点num
        lambdaUpdate().eq(File::getId, file.getFatherId()).setSql("file_num = file_num + 1").update();
        return true;
    }

    private void deleteFold(Long id) {
        // 1. 查找所有直接子项
        QueryWrapper<File> wrapper = new QueryWrapper<>();
        wrapper.eq("father_id", id);
        List<File> children = list(wrapper);

        // 2. 递归删除每个子项
        for (File child : children) {
            if (child.getType() != 2) {  // 如果是文件夹，先递归删除其内容
                deleteFold(child.getId());
            }
            removeById(child.getId());  // 删除当前子项
        }
    }
}
